#include "xmodule_config.h"

#include <stdint.h>

#include "rtl876x.h"
#include "rtl876x_gpio.h"
#include "rtl876x_pinmux.h"
#include "rtl876x_rcc.h"
#include "rtl876x_adc.h"
#include "rtl876x_nvic.h"

#include "boards.h"

static bool adc_multi_is_initialed = false;

void adc_multi_channel_init(void)
{
    if( adc_multi_is_initialed )
    {
        return;
    }
    
    ADC_DeInit( ADC ); 
    RCC_PeriphClockCmd( APBPeriph_ADC, APBPeriph_ADC_CLOCK, ENABLE ); 

    ADC_InitTypeDef adcInitStruct;
    ADC_StructInit( &adcInitStruct ); 
    // for( uint8_t i = 0; i < 16; i++)
    {
        adcInitStruct.schIndex[0] = EXT_SINGLE_ENDED( BATTERY_ADC_INDEX );   
        #if MODULE_CHECK_ENABLED( WATER_OIL )
        adcInitStruct.schIndex[1] = EXT_SINGLE_ENDED( WATER_OIL_VOLT_ADC_INDEX );               
        #endif
    }
    adcInitStruct.bitmap = 0x0003;
    adcInitStruct.adcSamplePeriod = 255; // 0.5us 
    ADC_Init( ADC, &adcInitStruct ); 
    ADC_INTConfig( ADC, ADC_INT_ONE_SHOT_DONE, ENABLE ); 

    adc_multi_is_initialed = true;
}

void adc_multi_channel_get_result(uint16_t* result)
{
    ADC_BypassCmd( BATTERY_ADC_INDEX, ENABLE ); 
    #if MODULE_CHECK_ENABLED( WATER_OIL )
    ADC_BypassCmd( WATER_OIL_VOLT_ADC_INDEX, ENABLE );
    #endif
    ADC_Cmd( ADC, ADC_One_Shot_Mode, ENABLE ); 
    while( ADC_GetIntFlagStatus( ADC, ADC_INT_ONE_SHOT_DONE) != SET );
    
    result[0]= ADC_ReadByScheduleIndex( ADC, 0 ); //15
    result[1] = ADC_ReadByScheduleIndex( ADC, 1 ); //15

    ADC_Cmd( ADC, ADC_One_Shot_Mode, DISABLE ); 
    ADC_ClearINTPendingBit( ADC, ADC_INT_ONE_SHOT_DONE ); 
}

uint16_t adc_multi_channel_get_battery_result(void)
{
    uint16_t result[2];
    adc_multi_channel_get_result( result );

    return result[0];
}
uint16_t adc_multi_channel_get_water_oil_result(void)
{
    uint16_t result[2];
    adc_multi_channel_get_result( result );

    return result[1];
}
